package com.hbnu.zhanglian.dao;

import java.sql.*;

public class DBUtil {
    // 改为 SQL Server 连接字符串
    private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=data;encrypt=false;trustServerCertificate=true";


    private static final String USERNAME = "sa";
    private static final String PASSWORD = "04261615";

    static {
        try {
            // 改为 SQL Server 驱动类
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.out.println("SQL Server驱动加载成功");
        } catch (ClassNotFoundException e) {
            System.err.println("SQL Server驱动加载失败");

            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void testConnection() {
        Connection conn = null;
        try {
            conn = getConnection();
            System.out.println("SQL Server数据库连接成功 - 数据库: data");
        } catch (SQLException e) {
            System.err.println("数据库连接失败: " + e.getMessage());

        } finally {
            close(conn, null, null);
        }
    }
}